package spring.cloud.tasks.executor.listener.election;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import spring.cloud.tasks.executor.utils.log.LogUtils;

@Slf4j
@Setter
@Getter
class LeaderElectionTaskListener implements NodeCacheListener {

    private final ElectionListenerHolder electionListener;

    public LeaderElectionTaskListener(ElectionListenerHolder electionListener) {
        this.electionListener = electionListener;
    }

    @Override
    public void nodeChanged() throws Exception {
        electionListener.nodeCacheOrTreeCacheManager.getExecutorService().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    LogUtils.debug(log, electionListener.taskId, "Leader host nodeChanged", electionListener.taskId);
                    if (electionListener.isShutdown) {
                        LogUtils.debug(log, electionListener.taskId, "ElectionListenerManager has been shutdown");
                        return;
                    }
                    if (!electionListener.leaderElectionService.hasLeader()) {
                        LogUtils.info(log, electionListener.taskId, "Leader crashed, elect a new leader now");
                        electionListener.leaderElectionService.leaderElection();
                        LogUtils.info(log, electionListener.taskId, "Leader election completed");
                    } else {
                        LogUtils.debug(log, electionListener.taskId, "Leader is already existing, unnecessary to election");
                    }
                } catch (Throwable t) {
                    LogUtils.error(log, electionListener.taskId, t.getMessage(), t);
                }
            }
        });
    }
}
